package com.gzk.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gzk.domain.Product;
import com.gzk.domain.ProductOrder;
import com.gzk.feignClients.ProductFeign;
import com.gzk.feignClients.StoreFeign;
import com.gzk.hrm.util.CodeGenerateUtils;
import com.gzk.mapper.ProductOrderMapper;
import com.gzk.service.IProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jake.Chen
 * @since 2022-02-07
 */
@Service
public class ProductOrderServiceImpl extends ServiceImpl<ProductOrderMapper, ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductFeign productFeingn;

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private StoreFeign storeFeign;

    @Override
    public String submitOrder(Map<String, Long> map) {
        System.out.println(map);
        Long productId = map.get("productId");
        Long number = map.get("number");
        //根据商品id查询商品
        Product product = productFeingn.get(productId);
        //生成订单
        ProductOrder order = initOrder(product,number);
        //保存订单
        productOrderMapper.insert(order);
        //减库存
        storeFeign.reduceStore(map);
        return order.getOrderNo();
    }

    /**
     * 生成订单
     * @param product
     * @param number
     * @return
     */
    private ProductOrder initOrder(Product product, Long number) {
        ProductOrder order = new ProductOrder();
        order.setName(product.getName());
        order.setPrice(product.getPrice());
        order.setNumber(number);
        order.setUserId(1L);
        order.setTotalPrice(product.getPrice().multiply(new BigDecimal(number)));
        order.setOrderNo(CodeGenerateUtils.generateOrderSn(1L));
        return order;
    }
}
